package cn.lingyangwl.agile.msg.push.manager;

import cn.lingyangwl.agile.model.module.tenant.*;
import cn.lingyangwl.agile.msg.push.mapper.*;
import cn.lingyangwl.agile.msg.push.model.entity.*;
import cn.lingyangwl.agile.msg.push.model.rqrs.history.*;
import cn.lingyangwl.framework.mybatis.plus.utils.*;
import cn.lingyangwl.framework.tool.core.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 消息推送 仓储层
 *
 * @author shenguangyang
 */
@Slf4j
@Repository
public class MsgHistoryManager extends ServiceImpl<MsgHistoryMapper, MsgHistory>
        implements IService<MsgHistory> {

    /**
     * 分页查询
     *
     * @return 分页数据
     */
    public IPage<MsgHistory> pageHistory(HistoryPageReq req) {
        LocalDateTime beginDateTime = req.getBeginLocalDateTime();
        LocalDateTime endDateTime = req.getEndLocalDateTime();

        LambdaQueryWrapper<MsgHistory> queryWrapper = Wrappers.<MsgHistory>lambdaQuery()
            .eq(Objects.nonNull(req.getNoticeId()), MsgHistory::getNoticeId, req.getNoticeId())
            .eq(StringUtils.isNotEmpty(req.getStatus()), MsgHistory::getStatus, req.getStatus())
            .eq(StringUtils.isNotEmpty(req.getChannelType()), MsgHistory::getChannelType, req.getChannelType())
            .eq(StringUtils.isNotEmpty(req.getToUser()), MsgHistory::getToUser, req.getToUser())
            .in(Objects.nonNull(req.getGroupId()), MsgHistory::getGroupId, req.getGroupId())
            .eq(StringUtils.isNotEmpty(req.getBizType()), MsgHistory::getBizType, req.getBizType())
            // 应对需要在主租户中查询所有租户(主租户和所有子租户场景), 需要前端传递 isQueryAllTenant 参数
            .eq(!TenantContext.get().isFilterTenant(), MsgHistory::getMainTenantId, TenantContext.get().getMainTenantId())
            .ge(Objects.nonNull(beginDateTime), MsgHistory::getPushTime, beginDateTime)
            .le(Objects.nonNull(endDateTime), MsgHistory::getPushTime, endDateTime)
            .orderByDesc(MsgHistory::getPushTime);
        return this.page(PageUtil.to(req), queryWrapper);
    }
}